package com.hctforgreen.greenservice;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.utils.MachineCodeUtil;
import com.hctforgreen.greenservice.utils.Utils;

/**
 * 申请解绑
 * 
 * @author wuhs 20150803
 * 
 */
public class UnbundlingActivity extends ParentActivity {
	
	private Activity context;
	private TextView view_titleTv;
	private ImageButton button_back;
	
	private EditText edit_name;
	private EditText edit_phone;
	private EditText edit_cross_code;
	private TextView link_get_code_help;
	private Button button_get_code;
	private Button button_submit;
	private Button button_cancel; 
	private final int topTime = 60*10; 
	private int Num = topTime;//倒数时间
	/**
	 * 是否停止倒数线程
	 */
	private boolean stop = false;
	/**
	 * 短信验证唯一码
	 */
	private String identity;
	@Override
	protected void onResume() {
		super.onResume();
		initSkinLayout();
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_unbundling);

		findView();
		showResults();
		setListensers();
		
	}

	private void findView(){
		view_titleTv = (TextView) findViewById(R.id.tv_title);
		button_back = (ImageButton) findViewById(R.id.btn_back);
		edit_name =  (EditText) findViewById(R.id.edit_name);
		edit_phone =  (EditText) findViewById(R.id.edit_phone);
		edit_cross_code =  (EditText) findViewById(R.id.edit_cross_code);
		
		link_get_code_help = (TextView) findViewById(R.id.link_get_code_help);
		button_get_code = (Button) findViewById(R.id.button_get_code);
		button_submit = (Button) findViewById(R.id.button_submit);
		button_cancel = (Button) findViewById(R.id.button_cancel);
		
	}
	
	
	private void showResults(){
		view_titleTv.setText(getString(R.string.get_cross_code_title_tv));
		if (getIntent().getExtras() != null) {
			String phone = getIntent().getExtras().getString("phone");
			edit_phone.setText(phone);
		} 
	}
	
	private void setListensers(){
		button_back.setOnClickListener(mOnClick);
		link_get_code_help.setOnClickListener(mOnClick);
		button_get_code.setOnClickListener(mOnClick);
		button_submit.setOnClickListener(mOnClick);
		button_cancel.setOnClickListener(mOnClick);
	}
	
	
	
	
	private OnClickListener mOnClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.link_get_code_help:
				Intent intent = new Intent();
				intent.setClass(context,UnbundlingHelpActivity.class);
				if (getIntent().getExtras() != null) {
					intent.putExtras(getIntent().getExtras());
				}
				startActivity(intent);
				break;
			case R.id.button_get_code:
				stop = false;
				final String phone = edit_phone.getText().toString().trim();
				final String username = edit_name.getText().toString().trim();
				if(username.trim().isEmpty()||phone.trim().isEmpty()){
					Toast.makeText(context, "请按要求填写完整！",
							Toast.LENGTH_SHORT).show();
					break;
				}
				if(phone.trim().length()!=11){
					Toast.makeText(context, "请正确填写11位电话号码！",
							Toast.LENGTH_SHORT).show();
					break;
				}
				
				
				final MachineCodeUtil codeUtil = new MachineCodeUtil(context);
				String time=String.valueOf(System.currentTimeMillis());
				String a=time.substring(time.length()-4,time.length());
				String imeiCode = codeUtil.getIMEICode();
				final String identityCode = imeiCode.substring(imeiCode.length()-4,imeiCode.length())+a;
				//  把按钮变成不可点击，并且显示倒计时（正在获取）  
				button_get_code.setClickable(false);  
				button_get_code.setText("重新获取(" + Num-- + ")"); 
				
				 new Thread(new Runnable() {  
	                public void run() {
	    				try {
//	    					Message message = new Message();
//	    					HctController controller = new HctController(UnbundlingActivity.this);
//		    				JSONObject json = controller.getAccountActivateCode(phone, username, identityCode);
//							if(json.getString("statusCode") != null){
//								if(!json.getString("statusCode").equals("1")){
//									//获取验证码成功则保存唯一码
//									identity = identityCode;
//								}
//								message.what = -1;
//								message.obj = json;
//								handler2.sendMessage(message); 
//							}
		                    for (int i = topTime; i > 0; i--) {  
		                        if (i <= 0||stop) { 
		                            break;  
		                        }else{
		                        	handler.sendEmptyMessage(-2);  
		                        	if(i==1){
			                        	handler.sendEmptyMessage(-3);
			                        }
		                            Thread.sleep(1000); 
		                        }
		                        
		                    }  
	    				}catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	                }  
	            }).start();  
	            
	            new Thread(new Runnable() {  
	                public void run() {
	                	Message message = new Message();
	    				try {
		    				HctController controller = new HctController(UnbundlingActivity.this);
		    				JSONObject json = controller.getAccountActivateCode(phone, username, identityCode);
							if(json.getString("statusCode") != null){
								if(!json.getString("statusCode").equals("1")){
									//获取验证码成功则保存唯一码
									identity = identityCode;
								}
								message.what = -1;
								message.obj = json;
								handler2.sendMessage(message); 
							}
		    				
	    				} catch (Exception e) {
							e.printStackTrace();
						}  
	                }  
	            }).start(); 
				break;
			case R.id.button_submit:
				final String phone2 = edit_phone.getText().toString().trim();
				final String username2 = edit_name.getText().toString().trim();
				final String activeCode = edit_cross_code.getText().toString().trim();
				final String identityCode2 = identity;
				if(username2.isEmpty()||phone2.isEmpty()||activeCode.isEmpty()){
					Toast.makeText(context, "请按要求填写完整！",
							Toast.LENGTH_SHORT).show();
					break;
				}
				if(identityCode2==null){
					Toast.makeText(context, "请重新获取验证码！",
							Toast.LENGTH_SHORT).show();
					break;
				}
				
				new Thread(new Runnable() {  
	                public void run() {
	                	Message message = new Message();
	                	
	    				try {
		    				HctController controller = new HctController(UnbundlingActivity.this);
		    				JSONObject json = controller.compareActivateCode(phone2, username2, identityCode2, activeCode);
							if(json.getString("statusCode") != null){
									message.what = -4;
									message.obj = json;
									handler2.sendMessage(message); 
							}
		    				
	    				} catch (Exception e) {
							e.printStackTrace();
						}  
	                }  
	            }).start(); 
				break;
			case R.id.button_cancel:
				finish();
				break;	
			default:
				break;
			}
		}

	};
	
	
	Handler handler2 = new Handler() {
		public void handleMessage(Message msg) { 
			if(msg.what == -1){
            	JSONObject json = (JSONObject) msg.obj;
            	try {
            		if(json.getString("statusCode").equals("1")){
            			//短信发送失败，停止倒数
            			stop = true;
            			button_get_code.setText("获取验证码");  
                    	button_get_code.setClickable(true); 
                    	Num = topTime;
                    	
					}
					String accountMsg = json.getString("accountMsg");
					Toast.makeText(context, accountMsg,
							Toast.LENGTH_SHORT).show();
				} catch (JSONException e) {
					e.printStackTrace();
				}
            }else if(msg.what == -4){
            	//返回解绑信息
            	JSONObject json = (JSONObject) msg.obj;
            	try {
            		String accountMsg = json.getString("accountMsg");
            		if(json.getString("statusCode").equals("1")){
    					Toast.makeText(context, accountMsg,
    							Toast.LENGTH_SHORT).show();
            		}else if(json.getString("statusCode").equals("0")){
            			Utils.notice(context, "", accountMsg, click_1);
            		}
            		
            		
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
            }
		}
	};
	
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {  
            if (msg.what == -2) {  
            	button_get_code.setText("重新获取(" + Num-- + ")");  
            } else if (msg.what == -3) {
            	//填写短信时限结束
            	button_get_code.setText("获取验证码");  
            	button_get_code.setClickable(true); 
            	Num = topTime;
            	link_get_code_help.setVisibility(View.VISIBLE);
            	identity = null;//时限结束，将唯一码重新设为null
            }
        }  
    };  
    android.content.DialogInterface.OnClickListener click_1 = new android.content.DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface arg0, int arg1) {
			finish();
		}
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}


}
